#include "download_list.h"
#include "generalsetstyle.h"
#include "listmenu.h"
#include <QDesktopServices>

void DownLoadList(QTableView *tableview,Ui::MainWindow *ui,QString DirPath,
                  MainWindow *parent,QString downloadpath,int currentRow)
{
    //获取模型
    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(tableview->model());
    QStandardItem *Item =model->item(currentRow,0);//一开始是0
    //歌曲名字
    MainWindow::MusicMetaDataBase metaData;
    metaData.title=Item->data(Qt::UserRole+0).toString();
   // qDebug()<<metaData.title;
    metaData.author=Item->data(Qt::UserRole+1).toString();
   // qDebug()<<metaData.author;
    metaData.albumTitle=Item->data(Qt::UserRole+2).toString();
    // qDebug()<<metaData.albumTitle;
    metaData.duration=Item->data(Qt::UserRole+3).toString();
     //qDebug()<<metaData.filepath;
    metaData.filename=Item->toolTip();
    qDebug()<<"文件名称"<<metaData.filename;
    metaData.filepath=downloadpath+QDir::separator()+metaData.filename;//下载路径
    DownLoadListLayout(ui,metaData,DirPath,parent);
    QFile file(QDir::currentPath()+QDir::separator()+"download_song.txt");

    if(file.exists())//如果文件存在
    {
        if (!file.open(QIODevice::Append | QIODevice::Text)) {
            qWarning() << "无法打开文件:" << file.errorString();
            return;
        }

    }
    else//如果不存在
    {
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            qWarning() << "无法打开文件:" << file.errorString();
            return;
        }
    }
    QTextStream out(&file);
    out << metaData.title+"\n";  // 写入音乐名称
    out << metaData.author+"\n";  // 写入歌曲艺术家
    out << metaData.albumTitle+"\n";  //写入歌曲专辑
    out << metaData.duration+"\n";  // 写入歌曲时长
    out << metaData.filename+"\n";  // 写入歌曲市场
    out << metaData.filepath+"\n";  // 写入音乐路径

    file.close();    // 自动关闭，但显式关闭是好习惯
}

void DownLoadListLayout(Ui::MainWindow *ui,MainWindow::MusicMetaDataBase metaData
                        ,QString DirPath,
                        MainWindow *parent)//下载一栏音乐列表布局
{
    qDebug() << "+++++++++++++++++-----------";
     //这一大串都是获取的歌曲的图片
    QMediaPlayer player;
    qDebug()<<metaData.filepath+".mp3";

        player.setSource(QUrl::fromLocalFile(metaData.filepath+".mp3"));
        QEventLoop loop;
        QObject::connect(&player, &QMediaPlayer::mediaStatusChanged, [&](QMediaPlayer::MediaStatus status) {
            qDebug() << "媒体状态变化:" << status;
            if (status == QMediaPlayer::LoadedMedia ) {
                loop.quit();
            }
        });
        loop.exec();


    QVariant coverData = player.metaData().value(QMediaMetaData::ThumbnailImage);
    //获取歌曲封面
    QImage image = coverData.value<QImage>();
    QPixmap pixmap = QPixmap::fromImage(image);

    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(ui->download_list->model());
    int newRow = model->rowCount();
    model->insertRow(newRow);//最后一行
    QStandardItem *item =model->item(newRow,0);//一开始是0
    if (!item) {
        item = new QStandardItem();
        model->setItem(newRow, 0, item);
    }
    item->setToolTip(metaData.filename);//文件名称,是在目录中显示的文件名称,不是歌曲在播放时显示的标题

    QStringList musicinfo;
    //标题,艺术家,专辑,时长,路径
    musicinfo<<metaData.title
              <<metaData.author
              <<metaData.albumTitle
              <<metaData.duration
              <<metaData.filepath;
    // 添加图片
    qDebug()<<metaData.filepath<<"++++++++++++++++++";
    if(!pixmap.isNull())
        item->setIcon(QIcon(pixmap));
    else
        item->setIcon(QIcon(":/icons/空图片.png"));
    item->setToolTip(metaData.filename);
    //可以从每个歌曲中获取“标题”等信息
    for(int i=0;i<musicinfo.count();i++)
    {
        item->setData(musicinfo[i],Qt::UserRole + i);
    }

    //qDebug()<<"++++++++++++++++++++";
    //歌曲名称
    for(int i=1;i<model->columnCount()-1;i++)
    {
        item =model->item(newRow,i);
        if (!item) {
            item = new QStandardItem();
            model->setItem(newRow,i, item);
        }
        item->setText(musicinfo[i-1]);
        item->setToolTip(musicinfo[i-1]);
        item->setTextAlignment(Qt::AlignCenter);
    }
    QWidget *widget = new QWidget();
    QHBoxLayout *layout = new QHBoxLayout(widget);
    // 创建删除按钮
    QPushButton *delbtn = new QPushButton();
    QPushButton *openfilebtn = new QPushButton();
    GeneralSetButtonStyle(delbtn,":/icons/删除.png",25,"删除");
    GeneralSetButtonStyle(openfilebtn,":/icons/文件夹.png",25,"打开所在目录");
    ui->download_list->setIndexWidget(model->index(newRow, 5), widget);
    //删除按钮
    MainWindow::connect(delbtn, &QPushButton::clicked,[delbtn, ui, parent]()
    {
        GetDownMusicDir(ui,delbtn,"delete",parent);
    });
    //打开所在目录
    MainWindow::connect(openfilebtn, &QPushButton::clicked,[ui, parent, openfilebtn]()
    {
        GetDownMusicDir(ui,openfilebtn,"opendir",parent);
    });
    //layout->addWidget(openfilebtn);
    layout->addWidget(delbtn);
}
//获取音乐文件所处的目录
void  GetDownMusicDir(Ui::MainWindow *ui,QPushButton *button,QString operation,MainWindow *parent)
{
    //获取文件所处位置
    QPoint buttonPos = button->mapTo(ui->download_list, QPoint(0, 0));
     qDebug()<<buttonPos;
    int currentRow = ui->download_list->rowAt(buttonPos.y());
    qDebug()<<currentRow;
    if(currentRow==-1)
        currentRow=ui->download_list->model()->rowCount();
    currentRow--;
    qDebug()<<currentRow<<"++";
    ui->music_list->selectRow(currentRow);
    //获取歌曲文件的文件名称
    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(ui->download_list->model());
    QStandardItem *item =model->item(currentRow,0);//一开始是0
    QString filepath=item->data(Qt::UserRole+4).toString();
    qDebug()<<filepath;
    QString filename = item->toolTip();
    QString escapedFilename = QRegularExpression::escape(filename);
    QRegularExpression delestring(escapedFilename);
    filepath.remove(delestring);
    //两个按钮两个操作
    if(operation=="opendir")//打开文件所处位置
    {
         QDesktopServices::openUrl(QUrl::fromLocalFile(filepath));
    }
    if(operation=="delete")//删除
    {
        DeleteSong(ui->download_list,filepath,parent,true,currentRow);
        model->removeRow(currentRow);
        if(!model->rowCount())//没有东西了就删除
        {
            QFile file(QDir::currentPath()+QDir::separator()+"download_song.txt");
            if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
                qWarning() << "无法打开文件:" << file.errorString();
                return;
            }
            file.resize(0); // 将文件大小设为0
            file.close();
        }
    }
}

//加载已经下载的歌曲
void MainWindow::loadDownLoadSong()
{
    QFile file(QDir::currentPath()+QDir::separator()+"download_song.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "无法打开文件:" << file.errorString();
        return;
    }
    qDebug()<<QDir::currentPath()+QDir::separator()+"download_song.txt";
    QTextStream in(&file);
    in.setEncoding(QStringConverter::Utf8);
    int lineNumber = 1;
    MainWindow::MusicMetaDataBase metaData;
    while (!in.atEnd()) {
        QString line = in.readLine();
        qDebug()<<line;
        //6行一次循环
        switch(lineNumber)
        {
            case 1: metaData.title=line;break;
            case 2: metaData.author=line;break;
            case 3: metaData.albumTitle=line;break;
            case 4: metaData.duration=line;break;
            case 5: metaData.filename=line;break;
            case 6:
                metaData.filepath=line;
                if(QFile::exists(metaData.filepath+".mp3"))
                    DownLoadListLayout(ui,metaData,DirPath,this);
                lineNumber=0;
                break;//重置
        }
        lineNumber++;
    }

    file.close();


}




